package logic

import (
	"context"
	"errors"
	"fmt"

	"videoProject/common/checkx"
	"videoProject/src/usermanage/api/internal/svc"
	"videoProject/src/usermanage/api/internal/types"
	"videoProject/src/usermanage/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterRequest) (resp *types.Registeresponse, err error) {
	// todo: add your logic here and delete this line

	if false == checkx.IsValidEmail(req.Email) {
		return nil, errors.New(fmt.Sprintf("邮箱格式不正确"))
	}
	if false == checkx.IsValidPhoneNumber(req.Phone) {
		return nil, errors.New("手机号码格式不正确")
	}

	if len(req.Password) < 6 {
		return nil, errors.New(fmt.Sprintf("密码长度不能小于6位"))
	}

	if false == checkx.IsValidCompare(req.Password, req.Confirmpassword) {
		return nil, errors.New(fmt.Sprintf("两次密码不一致"))
	}

	_, err = l.svcCtx.UserModel.FindOneByName(l.ctx, req.UserName)
	if err == nil {
		return nil, errors.New(fmt.Sprintf("名字已注册 ，请重新填写"))
	}

	if req.Email != "" {
		_, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
		if err == nil {
			return nil, errors.New(fmt.Sprintf("邮箱已注册，请更换邮箱或者直接登陆"))
		}
		//if err != model.ErrNotFound {
		//	return nil, err
		//}
	}

	if req.Phone != "" {
		_, err = l.svcCtx.UserModel.FindOneByPhone(l.ctx, req.Phone)
		if err == nil {
			return nil, errors.New(fmt.Sprintf("手机号码已注册，请更换手机号码或者直接登陆"))
		}
		//if err != model.ErrNotFound {
		//	return nil, err
		//}
	}

	user := model.User{
		Name:     req.UserName,
		Email:    req.Email,
		Phone:    req.Phone,
		Password: req.Password,
	}
	r, err := l.svcCtx.UserModel.Insert(l.ctx, &user)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("数据库插入失败"))
	}

	user.Id, err = r.LastInsertId()
	if err != nil {
		return nil, errors.New(fmt.Sprintf("获取id 失败"))
	}

	reply := types.UserReply{
		Id:       user.Id,
		UserName: user.Name,
		Email:    user.Email,
	}

	//resp.UserReply = reply
	resp = &types.Registeresponse{UserReply: reply}
	return resp, nil
}
